#include "cv.h"
#include "ml.h"
#include "highgui.h"
#include <string>

using namespace std;

//global vars
CvHaarClassifierCascade* cascade;
CvMemStorage* storage = cvCreateMemStorage(0);

/**
 * detect face
 * @param: 
 * @return: 
 */
void detectFace(IplImage* image, double scale = 1.3){
	static CvScalar colors[] = {
		{{0,0,255}},{{0,128,255}},{{0,255,255}},{{0,255,0}},
		{{255,128,0}},{{255,255,0}},{{255,0,0}},{{255,0,255}},
	};

	IplImage* gray = cvCreateImage(cvGetSize(image), 8, 1);
	IplImage* smallImg = cvCreateImage(cvSize(cvRound(image->width/scale), cvRound(image->height/scale)), 8, 1);

	cvCvtColor(image, gray, CV_BGR2GRAY);
	cvResize(gray, smallImg, CV_INTER_LINEAR);
	cvEqualizeHist(smallImg, smallImg);

	cvClearMemStorage(storage);
	CvSeq* objects = cvHaarDetectObjects(smallImg, cascade, storage, 1.1, 5, 0, cvSize(20, 20));

	for (int i=0; i < (objects ? objects->total : 0); i++) {
		CvRect* r = (CvRect*)cvGetSeqElem(objects, i);
		cvRectangle(image, cvPoint(r->x, r->y), cvPoint(r->x+r->width, r->y+r->height), colors[i%8]);
	}

	cvReleaseImage(&gray);
	cvReleaseImage(&smallImg);
}


/**
 * main
 * @param: 
 * @return: 
 */
void main(){
	string cascadeName = "haarcascade_frontalface_alt2.xml";
	cascade = (CvHaarClassifierCascade*)cvLoad(cascadeName.data(), 0, 0, 0);

	string windowNameIn = "in";
	string windowNameOut = "out";

	string imagePath = "jcy.jpg";
	IplImage* image = cvLoadImage(imagePath.data());
	cvShowImage(windowNameIn.data(), image);
	IplImage* imageOut;
	imageOut = cvCloneImage(image);
	detectFace(imageOut);
	cvShowImage(windowNameOut.data(), imageOut);

	cvWaitKey(0);

	cvReleaseImage(&image);
	cvReleaseImage(&imageOut);
	cvDestroyWindow(windowNameIn.data());
	cvDestroyWindow(windowNameOut.data());
}